package cn.jserv.ddns.service;

import cn.jserv.ddns.data.LoginVo;
import cn.jserv.ddns.data.RestfulResult;
import cn.jserv.ddns.util.HttpUtils;
import com.google.gson.Gson;
import com.huawei.hilink.openapi.plugin.PluginData;
import com.huawei.hilink.rest.AbstractRESTResource;
import com.huawei.hilink.rest.Response;
import com.huawei.hilink.util.Logger;
import com.huawei.hilink.util.LoggerFactory;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @author 蒋登伟
 * @create 2022-03-15 15:26
 */
public class RestfulService extends AbstractRESTResource {

    public void activate() {

    }

    public void deactivate() {

    }

    public RestfulService() {
        super("ddns");
        buildDescriptor("/api/ddns/login", HTTP_POST, LoginVo.class, "login");
        buildDescriptor("/api/ddns/check", HTTP_GET, null, "check");
    }

    protected Response login(LoginVo loginVo) {
        String token = loginVo.getToken();
        RestfulResult restfulResult = new RestfulResult();
        if (!doLogin(token)) {
            return Response.ok(restfulResult.setCode(-1).setMessage("登录失败")).build();
        }
        pluginDataHandle.setData("token", token);
        return Response.ok(restfulResult.setCode(0).setMessage("登录成功")).build();
    }

    protected Response check() {
        Map<String, String> config = pluginDataHandle.getDatas();
        String token = config.get("token");
        RestfulResult restfulResult = new RestfulResult();
        if (StringUtils.isEmpty(token)) {
            return Response.ok(restfulResult.setCode(-1).setMessage("请先登录或注册")).build();
        }
        if (!doLogin(token)) {
            return Response.ok(restfulResult.setCode(-1).setMessage("请重新登录")).build();
        }
        return Response.ok(restfulResult.setCode(0).setMessage("配置正确")).build();
    }

    protected void setPluginData(PluginData pluginData) {
        this.pluginDataHandle = pluginData;
    }

    protected void unsetPluginData(PluginData pluginData) {
        this.pluginDataHandle = null;
    }

    private boolean doLogin(String token) {
        try {
            HttpUtils.post("https://plugin.jserv.cn/ddns/login", GSON.toJson(new LoginVo(token)));
            return true;
        } catch (IOException e) {
            logger.exception("验证token失败", e);
            return false;
        }
    }

    private PluginData pluginDataHandle;

    private static final Gson GSON = new Gson();

    private static final Logger logger = LoggerFactory.getLogger(RestfulService.class);

}
